package com.qf.driver.mqtt.handler;

import com.qf.common.sdk.bean.MessageHeader;
import com.qf.common.sdk.bean.MessagePayload;
import com.qf.common.sdk.bean.MessageType;
import com.qf.common.sdk.bean.MqttMessage;
import com.qf.common.utils.JsonUtil;
import com.qf.driver.service.MqttReciveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;

/**
 * 接收emqx服务器topic主题中的传感器上报数据
 * @author 千锋健哥
 */
@Configuration
@Slf4j
public class MqttReciveHandler {

    @Autowired
    private MqttReciveService reciveService;

    /**
     * 接收emqx服务器传感器上报的数据并处理
     * mqttInputChannel对象在MqttConfig类中, 是上报数据的通道对象
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handlerValue() {
        return message -> {
            log.info("[driver-mqtt设备中心]接收数据:" + message.getPayload().toString());
            log.info("[driver-mqtt设备中心]接收数据的消息头:" + JsonUtil.toJsonString(message.getHeaders()));
            if (message != null) {
                //1. 设备发过过来的消息载荷
                MessagePayload messagePayload = new MessagePayload(String.valueOf(message.getPayload()),
                        MessageType.MQTT);
                //2. 设备发送过来的消息头
                MessageHeader messageHeader = new MessageHeader(message.getHeaders());
                //3. 将消息头和载荷封装成消息对象
                MqttMessage mqttMessage = new MqttMessage(messageHeader, messagePayload);
                //4. 调用service处理具体的数据内容
                reciveService.reciveValue(mqttMessage);
            } else {
                log.info("[driver-mqtt设备中心]接收到的数据为空");
            }
        };
    }
}
